import { getSts } from '@/api';
import OSS from 'ali-oss';

interface GetStsResType {
  AssumedRoleUser: {
    Arn: string;
    AssumedRoleId: string;
  };
  Credentials: {
    AccessKeyId: string;
    AccessKeySecret: string;
    SecurityToken: string;
  };
  RequestId: string;
}

export async function getOSSClient() {
  const { Credentials } = await getSts<GetStsResType>();

  return new OSS({
    accessKeyId: Credentials.AccessKeyId,
    accessKeySecret: Credentials.AccessKeySecret,
    stsToken: Credentials.SecurityToken,

    region: import.meta.env.VITE_REGION,
    bucket: import.meta.env.VITE_BUCKET,

    refreshSTSToken: async () => {
      const { Credentials } = await getSts<GetStsResType>();
      return {
        accessKeyId: Credentials.AccessKeyId,
        accessKeySecret: Credentials.AccessKeySecret,
        stsToken: Credentials.SecurityToken
      };
    },
    refreshSTSTokenInterval: 5 * 1000
  });
}
